﻿//this script is for using the average value of an arraylist to smooth a float

using UnityEngine;
using System.Collections;

public class FloatSmoothTool  {
	
	//this number set how many number we use for smoothing.
	public int SmoothNumber;
	//this number count which position in array we insert the current position of keyjointID
	int SmoothCount=0;
	//ArrayList smoothArr=new ArrayList();
	float[] smoothArr;

//	public ArrayList SmoothArr {
//		get {
//			return smoothArr;
//		}
//
//	}

	public float[] SmoothArr {
		get {
			return smoothArr;
		}
		
	}


	static public float iota=0.00001f;
	// Use this for initialization
	public FloatSmoothTool ()
	{
		SmoothNumber = 30;
		smoothArr=new float[SmoothNumber];
		for(int i=0;i<SmoothNumber;i++)
		{
			smoothArr[i]=0f;
			//smoothArr.Add(0f);
		}		
	}


	public FloatSmoothTool (int SmthNum)
	{
		SmoothNumber = SmthNum;
		smoothArr=new float[SmoothNumber];
		for(int i=0;i<SmoothNumber;i++)
		{
			smoothArr[i]=0f;
			//smoothArr.Add(0f);
		}		
	}




	// Update is called once per frame
//	void Update () {
//		
//	}
	
	public float GetFilteredValue()
	{
		float retVal=0f;
		for(int i=0;i<SmoothNumber;i++)
		{
			retVal+=(float)smoothArr[i];
		}
		retVal/=SmoothNumber;

		if(float.IsInfinity(retVal)||
		    (float.IsNaN(retVal)))
		{
			return 0f;
		}
		return retVal;		
	}
	
	//At the end of the smooth period, like when some guy get out of the detection period,
	//we must rewrite all the entried with zero.
	public void ClearAll()
	{
		for(int i=0;i<SmoothNumber;i++)
		{
			smoothArr[i]=0f;					
		}		
	}
	
	//this is a special function.
	//We do not only insert a float value, but also make some process during the first several frames of the smooth period
	//we will write all the Zero-value entry with the val , which is the current value.
	//Then we insert the val into (SmoothCount++)%SmoothNumber of arraylist
	//Pay attention to the way we compare the zero values.
	public void InsertValue(float val)
	{
		for(int i=0;i<SmoothNumber;i++)
		{
			//when we detect a qualified player, if any vec in SmoothArr is zero, we set it the current value
			float tmpv=(float)smoothArr[i];
			if(
				(Mathf.Abs(tmpv)<iota)
				)
			{
				smoothArr[i]=val;
			}						
		}	
		
		
		SmoothCount++;
		SmoothCount=SmoothCount%SmoothNumber;
		smoothArr[SmoothCount]=val;	
		
	}
	
	
	
	
}
